<template>
  <el-row :gutter="gutter" v-if="formData">
    <template v-for="(item, index) in jsonList" :key="index">
      <template v-if="item.options.children">
        <jax-form-group v-model="formData[item.options.name]" :json="item.options.children"></jax-form-group>
      </template>
      <component v-else :is="componentId" :xs="24" :sm="item.span" :md="item.span" :lg="item.span" :xl="item.span">
        <template v-if="$slots[item.options.name]">
          <slot :name="item.options.name"></slot>
        </template>
        <jax-form-item v-else v-model="formData[item.options.name]" v-bind="item.options">
          <template v-if="$slots[item.options.name + '-input']">
            <slot :name="item.options.name + '-input'"></slot>
          </template>
        </jax-form-item>
      </component>
    </template>
    <slot></slot>
  </el-row>
</template>

<script setup>
const emits = defineEmits(['update:modelValue'])
const props = defineProps({
  // 表单数据v-model
  modelValue: Object,
  data: Object,
  json: { type: Array, required: true }, // 表单结构
  gutter: { type: Number, default: 15 }, // 间隔
  grid: { type: Boolean, default: true }, // 网格化
})

const formData = computed({
  get: () => props.data || props.modelValue,
  set: (val) => emits('update:modelValue', val),
})

const componentId = computed(() => {
  if (props.grid) {
    return 'el-col'
  } else {
    return 'div'
  }
})

const jsonList = computed(() => {
  return extractToList(props.json)
})

/**
 * 把json中的多维数据提取成一维数据列表，并计算span大小
 */
function extractToList(data, span = 24) {
  let list = []

  data.map((item) => {
    if (Array.isArray(item)) {
      const newList = extractToList(item, 24 / item.length)
      list = list.concat(newList)
    } else {
      list.push({
        span: item.span || span,
        options: item,
      })
    }
  })

  return list
}
</script>

<style lang="scss" scoped></style>
